import React, { useEffect, useRef, useState } from 'react';
import AMapLoader from '@amap/amap-jsapi-loader';
import { Button, Popup, SearchBar, CapsuleTabs, Toast, Mask, } from 'antd-mobile'
import { EnvironmentOutline } from 'antd-mobile-icons'
import AudioPlayer from './audio/index';
import { useNavigate } from 'react-router-dom'
import { BackTop } from '@nutui/nutui-react'
import './scss/AMapExample.scss'
import { textToSpeech } from './audio/AudioPlayer';
window._AMapSecurityConfig = {
    securityJsCode: "e8cb186db8ce345f8f09f4253d6e8d1e",
};
var capitals = [{
    "citycode": "010",
    "adcode": "110000",
    "name": "北京市",
    "center": [116.407394, 39.904211]
}]
const AMapExample = (props) => {
    const mapRef = useRef()
    const [btnIsFixed, setBtnIsFixed] = useState(false)
    const [scrollTop, setScrollTop] = useState(0)
    const navigate = useNavigate()
    // const [capitals, setCapitals] = useState([])
    let [positions, setPositions] = useState({
        latitude: 0,
        longitude: 0
    })

    const [driver, setDriver] = useState([
        {
            "id":Date.now(),
            "citycode": "010",
            "adcode": "110000",
            "name": "孙师傅",
            "pai": "天C·88888",
            "tel": "1381111111",
            "img": 'https://img0.baidu.com/it/u=2955332398,1712446780&fm=253&fmt=auto&app=120&f=JPEG',
            "brand": "丰田"
        }, {
            "id":Date.now(),
            "citycode": "010",
            "adcode": "110000",
            "name": "张师傅",
            "pai": "天C·99999",
            "tel": "1591111111",
            "img": 'https://b0.bdstatic.com/1a9f35428327ffe8bccfae8dcc1cfae4.jpg',
            "brand": "奥迪"
        }, {
            "id":Date.now(),
            "citycode": "010",
            "adcode": "110000",
            "name": "刘师傅",
            "pai": "天C·77777",
            "tel": "1731111111",
            "img": 'https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0510%2F49568d71j00sd90qe0015d000hs00hsg.jpg&thumbnail=660x2147483647&quality=80&type=jpg',
            "brand": "宝马"
        }, {
            "id":Date.now(),
            "citycode": "010",
            "name": "赵师傅",
            "pai": "天C·77777",
            "tel": "1921111111",
            "img": "https://nimg.ws.126.net/?url=http%3A%2F%2Fdingyue.ws.126.net%2F2024%2F0511%2Fa6770944j00sdboa00014d200gn00gkg00gn00gk.jpg&thumbnail=660x2147483647&quality=80&type=jpg",
            "brand": "奔驰"

        }, {
            "id":Date.now(),
            "citycode": "010",
            "adcode": "110000",
            "name": "李师傅",
            "pai": "天C·55555",
            "tel": "1375280111",
            "img": "https://img0.baidu.com/it/u=1348067051,1044376663&fm=253&fmt=auto&app=138&f=JPEG",
            "brand": "大众",
        },
    ])

    const [origin, setOrigin] = useState(0)
    const [destination, setDestination] = useState(false)
    const [info, setInfo] = useState(JSON.parse(sessionStorage.getItem('result')) || {})
    const [steps, setSteps] = useState(JSON.parse(sessionStorage.getItem('result'))?.routes[0].steps || [])
    const [Jump, setJump] = useState(false)
    useEffect(() => {
        // console.log('origin', origin);
        // console.log(info);
        if (info.info === 'OK') {
            Toast.show({
                icon: 'success',
                content: '呼叫成功',
            })
            textToSpeech(`全程大约${(info.routes[0].distance > 1000 ? (info.routes[0].distance / 1000).toFixed(1) + '公里' : info.routes[0].distance + '米')}，请注意乘车安全，`, (url) => {
                const audio = new Audio(url);
                audio.play();
            })
            console.log(capitals);
            setJump(true)
            setVisible(false)
            setVisible1(false)
            setVisible2(false)
            // navigate('/home/amap', { state: {
            //     distance: info.routes[0].distance,
            //     time: info.routes[0].time,
            //     speed: Math.floor(Math.random() * 60) + 20,
            //     destinationName: info.destinationName,
            //     originName: info.originName,
            //     capitals:capitals[math.floor(Math.random() * capitals.length)]
            // } })
        }

    }, [destination])
    let [isCar, setIsCar] = useState(false)
    useEffect(() => {
        navigator.geolocation.getCurrentPosition(async (position) => {
            capitals = [
                {
                    "citycode": "010",
                    "adcode": "110000",
                    "name": "孙师傅",
                    "pai": "天C·88888",
                    "tel": "1381111111",
                    "center": [position.coords.longitude + (Math.random().toFixed(5) / 100), position.coords.latitude + (Math.random().toFixed(5) / 100)],

                }, {
                    "citycode": "010",
                    "adcode": "110000",
                    "name": "张师傅",
                    "pai": "天C·99999",
                    "tel": "1591111111",
                    "center": [position.coords.longitude + (Math.random().toFixed(5) / 100), position.coords.latitude + (Math.random().toFixed(5) / 100)]
                }, {
                    "citycode": "010",
                    "adcode": "110000",
                    "name": "刘师傅",
                    "pai": "天C·77777",
                    "tel": "1731111111",
                    "center": [position.coords.longitude + (Math.random().toFixed(5) / 100), position.coords.latitude + (Math.random().toFixed(5) / 100)]
                }, {
                    "citycode": "010",
                    "name": "赵师傅",
                    "pai": "天C·77777",
                    "tel": "1921111111",
                    "center": [position.coords.longitude + (Math.random().toFixed(5) / 100), position.coords.latitude + (Math.random().toFixed(5) / 100)]
                }, {
                    "citycode": "010",
                    "adcode": "110000",
                    "name": "李师傅",
                    "pai": "天C·55555",
                    "tel": "1375280111",
                    "center": [position.coords.longitude + (Math.random().toFixed(5) / 100), position.coords.latitude + (Math.random().toFixed(5) / 100)]
                },
            ]
        })
    }, [])
    const [massage, setMassage] = useState([
        {
            keyword: '',
            city: '河北'
        },
        {
            keyword: '',
            city: '河北'
        }
    ]);
    let [points, setPoints] = useState([
        { keyword: '北京协和医院', city: '河北' }, //起始点坐标
        { keyword: '邯郸火车站', city: '河北' } //终点坐标
    ])
    let infoWindow = {}
    useEffect(() => {
        // setPoints([...massage])
        navigator.geolocation.getCurrentPosition(async (position) => {
            setPositions({
                latitude: position.coords.latitude,
                longitude: position.coords.longitude
            })
            AMapLoader.load({
                "key": "93ac23764b679a2cfd4c8887ab99e648",   // 申请好的Web端开发者Key，首次调用 load 时必填
                "version": "2.0",   // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
                "plugins": [],  //插件列表
            }).then((AMap) => {
                let amap = new AMap.Map('mapContainer', { // mapcontainer为容器的id
                    rotateEnable: true,
                    pitchEnable: true,
                    zoom: 17,
                    pitch: 50,
                    rotation: -15,
                    zooms: [2, 20],
                    viewMode: '3D',
                    resizeEnable: true,
                    center: [position.coords.longitude, position.coords.latitude] //初始化地图中心点
                });

                // console.log(AMap.GeometryUtil.distance([position.coords.longitude, position.coords.latitude], capitals[0]?.center), "距离");



                // 标记
                let marker = new AMap.Marker({
                    // position: [position.coords.longitude, position.coords.latitude], // 基点位置
                });


                //引入和创建驾车规划插件
                AMap.plugin([
                    "AMap.Driving",
                    "AMap.MouseTool",
                    "AMap.ControlBar",
                    "AMap.ToolBar",
                    "AMap.Scale",
                    "AMap.CircleMarker",
                    "AMap.Geolocation",
                    "AMap.MapType"
                ], async function () {

                    //获取起终点规划线路
                    {
                        if (isCar) {
                            const driving = new AMap.Driving({
                                map: amap,
                                panel: "",
                            });
                            driving.search(points, function (status, result) {
                                // console.log(points,"points");
                                if (status === "complete") {
                                    //status：complete 表示查询成功，no_data 为查询无结果，error 代表查询错误
                                    //查询成功时，result 即为对应的驾车导航信息
                                    console.log(result, "result");
                                    setOrigin(result.routes[0].distance);
                                    setInfo(result)
                                    // localStorage.setItem('result', JSON.stringify(result))
                                    sessionStorage.setItem('result', JSON.stringify(result))
                                    setDestination(true)
                                    setSteps(result.routes[0].steps)
                                    setVisible(false)
                                } else {
                                    console.log("获取驾车数据失败：" + result);
                                }
                            })
                        }
                    }



                    //添加比例尺控件，展示地图在当前层级和纬度下的比例尺
                    amap.addControl(new AMap.Scale());

                    //添加类别切换控件，实现默认图层与卫星图、实施交通图层之间切换的控制
                    amap.addControl(new AMap.MapType({
                        // offset: [10, 20],  // 定位按钮的停靠位置的偏移量
                        position: {
                            left: '90px',
                            bottom: '150px'
                        },
                    }));

                    /**
                     * 3D控制罗盘
                     */
                    amap.addControl(new AMap.ControlBar({
                        position: {
                            right: '20px',
                            top: '20px'
                        },
                        showControlButton: true,  // 是否显示倾斜、旋转按钮。默认为 true
                    }));

                    var toolBar = new AMap.ToolBar({
                        position: {
                            right: '40px',
                            top: '110px'
                        }
                    });
                    toolBar.addTo(amap);

                    var geolocation = new AMap.Geolocation({
                        enableHighAccuracy: true, // 是否使用高精度定位，默认：true
                        timeout: 10000, // 设置定位超时时间，默认：无穷大
                        offset: [10, 20],  // 定位按钮的停靠位置的偏移量
                        zoomToAccuracy: true,  //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                        position: 'RB', //  定位按钮的排放位置,  RB表示右下
                        circleMarker: true, // 是否使用圆圈标记定位位置，默认：true
                        circleOptions: {
                            fillColor: '#ff6347',
                            strokeColor: '#ff6347',
                            strokeOpacity: 1,
                            strokeWeight: 1,
                            radius: 10,
                            strokeStyle: 'solid',
                        }
                    })
                    geolocation.getCurrentPosition(function (status, result) {
                        if (status == 'complete') {
                            onComplete(result)
                        } else {
                            // onError(result)
                        }
                    })
                    geolocation.addTo(amap);
                    let onComplete = (result) => {
                        // console.log(result, "result");
                        // result为具体的定位信息
                        var str = [];
                        str.push('定位结果：' + result.position);
                        str.push('定位类别：' + result.location_type);
                        if (result.accuracy) {
                            str.push('精度：' + result.accuracy + ' 米');
                        }
                        // 如为IP精确定位结果则没有精度信息
                        str.push('是否经过偏移：' + (result.isConverted ? '是' : '否'));
                        console.log(str);
                    }

                    /**
                     * 鼠标工具插件
                     */
                    var mouseTool = new AMap.MouseTool(amap);
                    //监听draw事件可获取画好的覆盖物
                    var overlays = [];
                    mouseTool.on('draw', function (e) {
                        overlays.push(e.obj);
                        console.log(e.obj);
                    })

                    function draw(type) {
                        switch (type) {
                            case 'marker': {
                                mouseTool.marker({
                                    //同Marker的Option设置
                                });
                                break;
                            }
                            case 'polyline': {
                                mouseTool.polyline({
                                    strokeColor: '#80d8ff'
                                    //同Polyline的Option设置
                                });
                                break;
                            }
                            case 'polygon': {
                                mouseTool.polygon({
                                    fillColor: '#00b0ff',
                                    strokeColor: '#80d8ff'
                                    //同Polygon的Option设置
                                });
                                break;
                            }
                            case 'rectangle': {
                                mouseTool.rectangle({
                                    fillColor: '#00b0ff',
                                    strokeColor: '#80d8ff'
                                    //同Polygon的Option设置
                                });
                                break;
                            }
                            case 'circle': {
                                mouseTool.circle({
                                    fillColor: '#00b0ff',
                                    strokeColor: '#80d8ff'
                                    //同Circle的Option设置
                                });
                                break;
                            }
                        }
                    }
                    draw('circle');
                });


                var center = capitals[Math.floor(Math.random() * capitals.length)].center;
                var circleMarker = new AMap.CircleMarker({
                    center: center,
                    radius: 5 + Math.random() * 3,//3D视图下，CircleMarker半径不要超过64px
                    strokeColor: 'white',
                    strokeWeight: 2,
                    strokeOpacity: 0.5,
                    fillColor: '#ff6347',
                    fillOpacity: 0.5,
                    zIndex: 10,
                    bubble: true,
                    cursor: 'pointer',
                    clickable: true,

                })
                circleMarker.setMap(amap)



                // 地图添加标记
                amap.add(marker);
            }).catch(e => {
                console.log(e);
            })
        })

    }, [isCar]);

    const [visible1, setVisible1] = useState(false);
    const [visible, setVisible] = useState(false);
    const [fixeds, setFixeds] = useState([
        {
            title: '家',
            key: 'home',
            position: localStorage.getItem('home') || ''
        }, {
            title: '学校',
            key: 'school',
            position: localStorage.getItem('school') || ''
        }, {
            title: '公司',
            key: 'company',
            position: localStorage.getItem('company') || ''
        }
    ]);
    const [visible2, setVisible2] = useState(false);
    const [positionKey, setPositionKey] = useState('');
    const [position, setPosition] = useState('');
    let Cap = () => {
        return <CapsuleTabs defaultActiveKey={''} activeKey={positionKey} className='capsule-tabs' onChange={(key) => {
            setPositionKey(key)
            if (fixeds.find(item => item.key === key).position === '') {
                Toast.show({
                    content: '请先选择地点',
                    afterClose: () => {
                        setVisible2(true)
                        setJump(false)
                    },
                })
                setJump(false)
                return
            }
            setVisible(true)
            setJump(false)
            setMassage([
                { keyword: '河北科技学院', city: '河北' }, //起始点坐标
                { keyword: fixeds.find(item => item.key === key).position, city: '河北' } //终点坐标
            ])
        }}>
            {
                fixeds.map((item, index) => {
                    return <CapsuleTabs.Tab title={item.title} key={item.key} />
                })
            }
        </CapsuleTabs>
    }
    return (
        <>
            <div
                id="mapContainer" style={{ width: '100%', position: 'relative' }}>
            </div>
            <div className='home-all'>
            
            {
                !!Jump && info.info === "OK" ? <div
                    style={{ transition: 'all .4s', transform: 'scale(1)' }}
                    onClick={() => {
                        navigate('/cart', { state: {
                            distance: info.routes[0].distance,
                            time: info.routes[0].time,
                            speed: Math.floor(Math.random() * 60) + 20,
                            destinationName: info.destinationName,
                            originName: info.originName,
                            text:"",
                            capitals:driver[Math.floor(Math.random() * driver.length)]
                        } })
                        // console.log(info,capitals[Math.floor(Math.random() * capitals.length)],);
                    }}
                    className='searchExample-Jump'>
                    跳
                </div> : ''
            }
            <Mask visible={visible2} onMaskClick={() => setVisible(false)}>
                <div className={'overlayContent'}>
                    <div className={'overlayContent-title'}>请选择地点</div>
                    <SearchBar
                        value={position}
                        onChange={(value) => {
                            setPosition(value)
                        }}
                        block className='search-map-start' icon={<EnvironmentOutline />}></SearchBar>
                    <Button
                        className='overlayContent-btn overlayContent-yes'
                        block onClick={() => {
                            setFixeds(
                                fixeds.map((item, index) => {
                                    if (item.key === positionKey) {
                                        return { ...item, position: position }
                                    }
                                    return item
                                })
                            )
                            localStorage.setItem(positionKey, position)
                            setVisible2(false)
                            setJump(true)
                        }}>确定</Button>
                    <Button
                        className='overlayContent-btn'
                        block onClick={() => {
                            setVisible2(false)
                            setJump(true)
                        }}>取消</Button>
                </div>
            </Mask>

            <Cap></Cap>
            <SearchBar
                cancelText={'查看路线'}
                showCancelButton={() => true}
                onCancel={() => {
                    console.log(points);
                    if (points[0]?.keyword === "" || points[1]?.keyword === "") {
                        // message.warning('请输入起点和终点')
                        Toast.show({
                            content: '请输入起点和终点',
                            afterClose: () => {
                                console.log('after')
                            },
                        })
                        return
                    }
                    setVisible1(true)
                    setJump(false)
                }}
                className='search-map-bottom' placeholder='请输入内容' icon={<EnvironmentOutline />}
                onFocus={() => {
                    setVisible(true)
                    setJump(false)
                }}
            />
            <Popup
                visible={visible1}
                onMaskClick={() => {
                    setVisible1(false)
                }}
                onClose={() => {
                    setVisible1(false)
                }}
                forceRender={true}
                bodyStyle={{ height: '60vh' }}
            >
                <div ref={mapRef}
                    onScroll={(e) => {
                        // 获取当前滚动条滚动高度
                        setScrollTop(e.target.scrollTop)
                        // 获取当前滚动条滚动高度对应的索引
                        const index = Math.floor(scrollTop / 40);
                        console.log(scrollTop);
                        if (scrollTop > 200) {
                            setBtnIsFixed(true)
                        } else {
                            setBtnIsFixed(false)
                        }
                    }}
                    className='amap-example' id='amapExample'>
                    <Button
                        className={btnIsFixed ? 'overlayContent-btn-close' : 'overlayContent-btn-none'}
                        block={!btnIsFixed}
                        style={{ transition: 'all .5s' }}
                        onClick={() => {
                            if (!btnIsFixed) {
                                setVisible1(false)
                                setJump(true)
                            } else {
                                mapRef.current.scrollTop = 0
                                setScrollTop(0)
                            }
                        }}>
                        {
                            !btnIsFixed ?
                                '关闭'
                                : '确定'
                        }
                    </Button>
                    <div className='amap-lib-driving'>
                        <dl class="plan plan-nobus" style={{ display: 'block' }}>
                            {
                                steps.length > 0 ?
                                    <dt className='start'>
                                        <div className='beforedt'></div>
                                        <div className='afterdt'></div>
                                        <b>{info.originName}</b>
                                    </dt>
                                    : ''
                            }
                            {
                                steps.map((item, index) => {
                                    return (
                                        <dt className={'route' + ' ' + (
                                            /左前/.test(item.action) ? 'turn-leftup' :
                                                /靠左/.test(item.action) ? 'turn-keepleft' :
                                                    /右前/.test(item.action) ? 'turn-rightup' :
                                                        /靠右/.test(item.action) ? 'turn-keepright' :
                                                            /左/.test(item.action) ? 'turn-left' :
                                                                /右/.test(item.action) ? 'turn-right' : 'turn-slow'
                                        )}
                                            key={index}
                                        >
                                            <div className='beforedt'></div>
                                            <div className='afterdt'></div>
                                            {item.instruction}
                                        </dt>
                                    )
                                })
                            }
                            <BackTop target="target" />
                            {
                                steps.length > 0 ?
                                    <dt className='end'>
                                        <div className='beforedt'></div>
                                        <b>{info.destinationName}</b>
                                    </dt>
                                    : ''
                            }
                        </dl>
                    </div>
                </div>
            </Popup>

            <Popup
                visible={visible}
                onMaskClick={() => {
                    setVisible(false)
                }}
                onClose={() => {
                    setVisible(false)
                }}
                forceRender={true}
                bodyStyle={{ height: '30vh' }}
            >
                <div className='searchExample'>
                    <SearchBar placeholder='当前位置' icon={<EnvironmentOutline />}
                        value={massage[0].keyword}
                        onChange={(e) => {
                            massage[0].keyword = e
                            setMassage([...massage])
                            console.log(massage);
                        }}
                        className='search-map-start'
                    />

                    <SearchBar
                        className='search-map-end'
                        placeholder='请输入目的地' icon={<EnvironmentOutline />}
                        value={massage[1].keyword}
                        onChange={(e) => {
                            massage[1].keyword = e
                            setMassage([...massage])
                        }}
                    />
                    <AudioPlayer origin={origin}
                        onClick={() => {
                            setIsCar(false)
                            setPoints([...massage])
                            console.log(massage);
                            // setVisible1(true)
                            setTimeout(() => {
                                setIsCar(true)
                            }, 1000)
                            console.log(origin);
                            // navigate('/map', {
                            //     state: {
                            //         origin: origin,
                            //     }
                            // })
                        }}
                    ></AudioPlayer>
                    <Button
                        className='search-map-btn'
                        block onClick={() => {
                            setVisible(false)
                            setJump(true)
                        }}>取消</Button>
                </div>
            </Popup>
            </div>
        </>
    );
};

export default AMapExample;
/*
————————————————

                            版权声明：本文为博主原创文章，遵循 CC 4.0 BY-SA 版权协议，转载请附上原文出处链接和本声明。
                        
原文链接：https://blog.csdn.net/weixin_40381947/article/details/131384418
*/